﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WxPayAPI;
using Yule8xCommon.Applib;
using Yule8xCommon.Db;
using Yule8xCommon.Typelib;

namespace Yule8xModel.PageModels
{
    /// <summary>
    /// 微信支付回调页面模型类
    /// </summary>
    public class WxPayResultNotifyPageModels
    {
        // 购买钻石
        public static bool BuyCardPay(string out_trade_no, int rebate_amount, decimal parent1_commission_rate, decimal parent2_commission_rate, out string return_msg)
        {
            // 解析参数
            string attach = DbFactory.Init(AppInfo.conn_yule8x_agent).GetValue(string.Format("select paramstr from t_finance_recharge where out_trade_no='{0}'", out_trade_no), string.Empty).ToString();
            if (string.IsNullOrEmpty(attach))
            {
                return_msg = string.Format("[微信支付通知页面-购买钻石] WxPayResultNotifyPageModels.BuyCardPay 充值记录无效![OTN:{0}]", out_trade_no);
                return false;
            }
            // string amount = notifyData.GetValue("total_fee").ToString(); // 因为微信支付实际是1分钱，改为从参数获取

            string attachvaluestr = attach.Substring(attach.IndexOf(':') + 1);
            BuyDiamondAttachData attadata = JSON.parse<BuyDiamondAttachData>(attachvaluestr);
            int uid = attadata.uid;
            int dimond_number = attadata.num;
            decimal payamount = attadata.amo; // 因为微信支付实际是1分钱，改为从参数获取
            string payfor = attadata.pfor; // 为自己购买(payforme)或为别人购买(payforother)
            int game_id = attadata.guid;
            int game_mact_id = attadata.gmid;
            //string game_nickname = attadata.gnn;
            string game_nickname = string.Empty;
            int game_currency_number = attadata.gnum;
            int is_event = attadata.isevent;
            string reason = string.Empty;

            LogUtil.Instance.WriteInfo(string.Format("[微信支付通知页面-购买钻石] attachvaluestr={0}", attachvaluestr));

            if ("payforme" == payfor)
            {
                if (UserModels.CheckUserIsAgent(uid))
                {
                    game_nickname = UserModels.GetNickName(uid);
                }
            }

            if (string.IsNullOrEmpty(game_nickname))
            {
                switch (game_mact_id)
                {
                    case 1:
                        // 查询游戏库的用户昵称
                        game_nickname = BozhongGameUtil.GetNickName(game_id);
                        break;
                    case 2:
                        // 查询游戏库的用户昵称
                        game_nickname = WanghuGameUtil.GetNickName(game_id);
                        break;
                }
            }

            decimal parent1_amount = payamount * parent1_commission_rate; // 上级是代理, 获得25%返佣
            decimal parent2_amount = payamount * parent2_commission_rate; // 上上级是代理, 获得15%返佣
            string paramstr = string.Empty;
            string sqlstmt = string.Empty;
            bool result = UserModels.PayForByDimond(uid, payfor, game_mact_id, game_id, game_nickname, payamount, dimond_number, parent1_amount, parent2_amount, AppInfo.EncryptKey, out_trade_no, is_event, out return_msg);

            LogUtil.Instance.WriteInfo(string.Format("============[微信支付通知页面-购买钻石-结果]================== 充值结果：result={0}, message={1}, attachvaluestr={2}", result, return_msg, attachvaluestr));

            if (result)
            {
                bool isAgent = UserModels.CheckUserIsAgent(uid);
                // 如果用户不是代理则直接给指定的游戏ID增加到游戏表
                if (is_event == 0 && "payforme" == payfor && isAgent)
                {
                    // 不处理
                }
                else
                {
                    if (AppInfo.ForbidUpdateGameMode && AppInfo.IsDebugMode)
                    {
                        // 必需是调试模式，禁止更新游戏数据库才有效，否则一不小心勾选了禁止更新游戏库，即使没有调试也会禁止更新，那就不行了
                        // 调试模式，(原则：游戏库只能读，不能修改) 直接跳过后续游戏库更新操作
                        return_msg = string.Format("[调试模式:::微信支付通知页面-购买钻石] 游戏库只能读, 不能修改, 支付成功, 更新游戏库货币操作：gameid={0}, diamond_number={1},game_currency_number={2}, mact_id={3}", game_id, dimond_number, game_currency_number, game_mact_id);
                        LogUtil.Instance.WriteError(return_msg, null);
                        game_mact_id = 0;
                    }
                    sqlstmt = string.Empty;
                    switch (game_mact_id)
                    {
                        case 1:
                            // 更新泊众房卡
                            result = BozhongGameUtil.UpdateRoomCard(game_id, dimond_number);
                            if (!result)
                            {
                                return_msg = "[微信支付通知页面-购买钻石] 支付成功, 但更新泊众房卡数据出错：" + return_msg;
                                LogUtil.Instance.WriteError(return_msg, null);
                            }
                            else
                            {
                                LogUtil.Instance.WriteInfo("[微信支付通知页面-购买钻石] 支付成功, 更新泊众房卡数据成功! " + attachvaluestr);
                            }
                            break;
                        case 2:
                            // 更新网狐游戏豆
                            GameUserInfoModel wanghuuser = WanghuGameUtil.GetGameUserInfo(game_id);
                            if (null == wanghuuser)
                            {
                                return_msg = "[微信支付通知页面-购买钻石] 支付成功, 但更新网狐游戏豆数据出错：用户不存在, game_uid=" + game_id;
                                LogUtil.Instance.WriteError(return_msg, null);
                            }
                            else
                            {
                                result = WanghuGameUtil.UpdateYouxidou(wanghuuser.UserID, wanghuuser.Accounts, game_currency_number, out return_msg);
                                if (!result)
                                {
                                    return_msg = "[微信支付通知页面-购买钻石] 支付成功, 但更新网狐游戏豆数据出错：" + return_msg;
                                    LogUtil.Instance.WriteError(return_msg, null);
                                }
                                else
                                {
                                    LogUtil.Instance.WriteInfo("[微信支付通知页面-购买钻石] 支付成功, 更新网狐游戏豆数据成功! " + attachvaluestr);
                                }
                            }
                            break;
                    }
                }
            }

            return result;
        }

        // 代理注册支付
        public static bool AgentRegistPay(string out_trade_no, string attach, int number, decimal amount, int rebate_amount, decimal parent1_commission_rate, decimal parent2_commission_rate, out string return_msg)
        {
            LogUtil.Instance.WriteInfo("[微信支付通知页面-代理注册支付]");
            // 解析参数
            // string amount = notifyData.GetValue("total_fee").ToString(); // 因为微信支付实际是1分钱，改为从参数获取
            // attach = string.Format("agentregist:{0},{1}", uid, unionid)
            string attachvaluestr = attach.Substring(attach.IndexOf(':') + 1);
            string[] attachvaluesarr = attachvaluestr.Split(',');
            int uid = int.Parse(attachvaluesarr[0]);

            LogUtil.Instance.WriteInfo(string.Format("[微信支付通知页面-代理注册支付] attachvaluestr={0}, uid={1}, number={2}, amount={3}", attachvaluestr, uid, number, amount));

            decimal parent1_amount = amount * parent1_commission_rate; // 上级是代理, 获得25%返佣
            decimal parent2_amount = amount * parent2_commission_rate; // 上上级是代理, 获得15%返佣
            string paramstr = string.Empty;
            bool result = UserModels.PayForAgentRegist(uid, amount, number, rebate_amount, parent1_amount, parent2_amount, AppInfo.EncryptKey, out_trade_no, out return_msg);

            LogUtil.Instance.WriteInfo(string.Format("[微信支付通知页面-代理注册支付] result={0}, message={1}", result, return_msg));

            return result;
        }
    }
}
